package com.ys.otms.services;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArrayList;

public class ApiClientTest {
    private static final ThreadLocal<Socket>
            threadConnect = new ThreadLocal<Socket>();
    private static Socket client;
    private static OutputStream outStr = null;
    private static InputStream inStr = null;
    private static PrintWriter out = null;
    private static BufferedReader reader = null;

    public static Thread tRecv =null;
    public static List<String> list = new CopyOnWriteArrayList<String>();
    public static Date last_recv_time = null;
    public static Date insrt_connection_time = null;
    public static ApiClientTest.KeepAliveTask myTask=null;
    public static boolean connect() {
        boolean flag=false;
        try{
            String host = "59.110.50.80";
            int port = 6081;
            client = threadConnect.get();
            if (client == null) {
                client=new Socket();
                SocketAddress socAddress = new InetSocketAddress(host, port);
                client.connect(socAddress, 15000);
                threadConnect.set(client);
                insrt_connection_time=new Date();
// logger.info("========链接开始！========");
            }
            outStr = client.getOutputStream();
            inStr = client.getInputStream();
            flag=true;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    public static void disconnect() {
        try {
            outStr.close();
            inStr.close();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class KeepAliveTask extends TimerTask {
        public KeepAliveTask() {
        }
        @Override
        public void run() {
            try {
                Date nowDate=new Date();
                // 当时前间与最后一次接收到数据的时间超过一小时,
                if(last_recv_time==null){
                    if(insrt_connection_time!=null){
                        if(insrt_connection_time.getTime() - last_recv_time.getTime() > 3600 * 1000){
                            boolean flag=ApiClientTest.connect();
                            Thread.sleep(1000);
                            if(flag){
                                if(ApiClientTest.myTask!=null){
                                    myTask.cancel();
                                }
                                if(ApiClientTest.tRecv!=null){
                                    ApiClientTest.tRecv.interrupt();
                                }
//                                logger.info("=====================重新建立客户端==============");
                                ApiClientTest spireApiProcess = new ApiClientTest();
                                ApiClientTest.tRecv = new Thread(spireApiProcess. new RecvThread());
                                ApiClientTest.tRecv.start();
                            }
                        }
                    }else{
                        boolean flag=ApiClientTest.connect();
                        Thread.sleep(1000);
                        if(flag){
                            if(ApiClientTest.myTask!=null){
                                myTask.cancel();
                            }
                            if(ApiClientTest.tRecv!=null){
                                ApiClientTest.tRecv.interrupt();
                            }
// logger.info("=====================重新建立客户端==============");
                            ApiClientTest spireApiProcess = new ApiClientTest();
                            ApiClientTest.tRecv = new Thread(spireApiProcess. new RecvThread());
                            ApiClientTest.tRecv.start();
                        }
                    }
                }
                if (nowDate.getTime() - last_recv_time.getTime() > 3600 * 1000) {
                    boolean flag=ApiClientTest.connect();
                    Thread.sleep(1000);
                    if(flag){
                        if(ApiClientTest.myTask!=null){
                            myTask.cancel();
                        }
                        if(ApiClientTest.tRecv!=null){
                            ApiClientTest.tRecv.interrupt();
                        }
// logger.info("=====================重新建立客户端==============");
                        ApiClientTest spireApiProcess = new ApiClientTest();
                        ApiClientTest.tRecv = new Thread(spireApiProcess. new RecvThread());
                        ApiClientTest.tRecv.start();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    class RecvThread implements Runnable {
        public void run() {
            try {
                Timer timer = new Timer();
                ApiClientTest spireApiProcess = new
                        ApiClientTest();
                myTask = spireApiProcess.new KeepAliveTask();
//1个小时之后执行,判断是否接收到数据,如果没有接收到,当前线程会自动重连,定时器在1小时之后执行
                timer.schedule(myTask, 60*60*1000, 60*60*1000 );
                out = new PrintWriter(outStr, true);
                reader = new BufferedReader(new InputStreamReader(inStr));
                out.println("{\"key\": \"904f181286c6428b9988a4b0f1eea38f\"}");
// logger.info("==============开始接收数据===============");
                String inData;
                while ((inData = reader.readLine()) != null)
                {
                    last_recv_time=new Date();
                    System.out.println(inData);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        boolean flag=ApiClientTest.connect(); //初始化一个连接
        if(flag){
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//接收线程
            ApiClientTest spireApiProcess = new ApiClientTest();
            ApiClientTest.tRecv = new Thread(spireApiProcess. new RecvThread());
            ApiClientTest.tRecv.start();
        }else{
//初始化连接失败
        }
    }
}
